import ZenRequest from './zen_request.js';
import Config from './config.js';
import RTLog from './rt_log.js';

const DEFAULT_MPID = 'zhidamp00';

export default {
    getProductConfig(mpid) {
        return new Promise((resolve, reject) => {
            const url = `/test_product/config/${mpid}`;
            ZenRequest.get(url, {}).then(
                (res) => {
                    if (res && res.h5_config) {
                        resolve(res);
                    } else {
                        reject({
                            msg: res
                        });
                    }
                },
                (err) => {
                    reject(err);
                }
            );
        });
    },
    createMakeImageTask(mpid, answers) {
        let userInfo = wx.getStorageSync('__session__');
        let newUserInfo = userInfo ? JSON.parse(userInfo) : getApp().mox.user;
        console.log('作图----------',newUserInfo);
        const options = {
            answers: answers,
            nickname:  newUserInfo?.nickName || newUserInfo?.nickname  || '',
            headimgurl: newUserInfo?.avatarUrl || newUserInfo?.avatar || Config.defaultUserHead,
            appid: 'wx5b5cadb2d78b45d5' || getApp().mox.appid,
            openid: newUserInfo.openid || '',
            sex: newUserInfo.gender || 0,
            city: newUserInfo.city,
            province: newUserInfo.province,
            country: newUserInfo.country,
            platform: 'WxH5',
            mp_openid: '',
            complex: 0,
            mpid: '',
            product_name: '',
            author: '',
            ad: '0',
            userid: newUserInfo.openid || '',
            mp_from: '',
            h5_test_related: {
                from: '',
                tid: '',
                oid: '',
                spt: ''
            }
        };

        return ZenRequest.post(`/test_product/v4/${mpid}`, JSON.stringify(options));
    },
    getMakeImageTaskResult(taskId) {
        return new Promise((resolve, reject) => {
            this._tryGetTaskResult(taskId, 15, (ret, data) => {
                if (ret) {
                    resolve(data);
                } else {
                    reject(data);
                }
            });
        });
    },
    _tryGetTaskResult(taskId, retry, cb) {
        if (retry) {
            let timeout = Math.max(200 + (21 - retry) * 100, 500);
            timeout = Math.min(timeout, 4000);
            setTimeout(() => {
                ZenRequest.get(`/test_product/v4/task/${taskId}`).then(
                    (res) => {
                        cb(true, res);
                    },
                    () => {
                        this._tryGetTaskResult(taskId, retry - 1, cb);
                    }
                );
            }, timeout);
        } else {
            cb(false, {
                msg: '查询出错'
            });
        }
    },
    getProductList() {
        return new Promise((resolve) => {
            this.getProductConfig(DEFAULT_MPID).then(
                (product_config) => {
                    product_config.h5_config = product_config.h5_config || {};
                    if (
                        product_config.h5_config.suggest &&
                        product_config.h5_config.suggest.length
                    ) {
                        wx.setStorage({
                            key: 'products',
                            data: product_config.h5_config.suggest
                        });

                        resolve(product_config.h5_config.suggest);
                    } else {
                        wx.getStorage({
                            key: 'products',
                            success: (res) => {
                                if (res.data) {
                                    resolve(res.data);
                                } else {
                                    resolve(Config.defaultProducts);
                                }
                            },
                            fail: (err) => {
                                resolve(Config.defaultProducts);
                            }
                        });
                    }
                },
                (err) => {
                    resolve(Config.defaultProducts);
                    RTLog.error('getProductList:getProductConfig fail! err:', err);
                }
            );
        });
    },
    getProductAdvertiseList() {
        return new Promise((resolve) => {
            this.getProductConfig(DEFAULT_MPID).then(
                (product_config) => {
                    product_config.h5_config = product_config.h5_config || {};
                    if (
                        product_config.h5_config.product_advertise_list &&
                        product_config.h5_config.product_advertise_list.length
                    ) {
                        wx.setStorage({
                            key: 'product_advertise_list',
                            data: product_config.h5_config.product_advertise_list
                        });

                        resolve(product_config.h5_config.product_advertise_list);
                    } else {
                        wx.getStorage({
                            key: 'product_advertise_list',
                            success: (res) => {
                                if (res.data) {
                                    resolve(res.data);
                                } else {
                                    resolve(Config.defaultProductsAdvertiseList);
                                }
                            },
                            fail: (err) => {
                                resolve(Config.defaultProductsAdvertiseList);
                            }
                        });
                    }
                },
                (err) => {
                    resolve(Config.defaultProductsAdvertiseList);
                    RTLog.error('getProductAdvertiseList:getProductAdvertiseList fail! err:', err);
                }
            );
        });
    },
    setLatestMp(mpid) {
        mpid &&
            wx.setStorage({
                key: 'latest_mpid',
                data: mpid
            });
    },
    getLatestMp() {
        return wx.getStorageSync('latest_mpid');
    },
    getAdsConfig() {
        return new Promise((resolve) => {
            this.getProductConfig(DEFAULT_MPID).then(
                (productConfig) => {
                    productConfig.h5_config = productConfig.h5_config || {};

                    resolve(productConfig.h5_config.advertisements || {});
                },
                () => {
                    resolve({});
                }
            );
        });
    },
    getConfig(mpid) {
        mpid = mpid || DEFAULT_MPID;
        return new Promise((resolve) => {
            this.getProductConfig(mpid).then(
                (cfg) => {
                    cfg.h5_config = cfg.h5_config || {};
                    resolve(cfg.h5_config);
                    // resolve(Util.assignDeep(Config.defaultSettings, cfg.h5_config));
                },
                () => {
                    resolve(Config.defaultSettings);
                }
            );
        });
    }
};
